package com.hcss.common.interceptor;

import com.hcss.common.base.BaseClass;
import com.hcss.common.util.EmptyUtil;
import com.hcss.sys.menu.model.HcSysMenu;
import com.hcss.sys.modulelog.constant.ModulelogConstants;
import com.hcss.sys.modulelog.model.HcSysModulelog;
import com.hcss.sys.modulelog.queue.ModuleLogServiceQueue;
import com.hcss.sys.role.dao.HcSysRoleComplexMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @描述: 菜单请求拦截
 * @作者: fengzhaodong
 * @创建日期: 2018-09-30 13:51
 * @公司 浙江鸿程计算机系统有限公司
 */
@Slf4j
public class URLInterceptorLog implements HandlerInterceptor {

    private final HcSysRoleComplexMapper hcSysRoleComplexMapper;


    public URLInterceptorLog(HcSysRoleComplexMapper hcSysRoleComplexMapper) {
        this.hcSysRoleComplexMapper = hcSysRoleComplexMapper;

    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取用户菜单列表
        try {
            List<HcSysMenu> menuList = hcSysRoleComplexMapper.getMenuByUserid(BaseClass.getSessionUserid());
            if (!EmptyUtil.isEmpty(menuList)) {
                //获取访问路径
                String servletPath = httpServletRequest.getServletPath();
                for (HcSysMenu menu : menuList) {
                    String menuUrl = menu.getUrl();
                    menuUrl = menuUrl.replaceAll("\\*\\*", "\\\\w(/\\\\w)*");
                    menuUrl = menuUrl.replaceAll("\\*", "\\\\w*");
                    //访问路径在菜单列表中，记录
                    if (Pattern.matches("^" + menuUrl + "$", servletPath)) {
                        HcSysModulelog hcSysModulelog = new HcSysModulelog();
                        hcSysModulelog.setUserid(BaseClass.getSessionUserid());
                        hcSysModulelog.setModuleurl(servletPath);
                        hcSysModulelog.setModulename(menu.getName());
                        hcSysModulelog.setLogtype(ModulelogConstants.logType.MODULE_LOG);
                        ModuleLogServiceQueue.getInstance().put(hcSysModulelog);
                    }
                }
            }
        } catch (Exception e) {
            log.error("记录菜单访问日志出错：", e);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}


